package com.cmcc.aregister.ui.activity;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bypay.other.v;
import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.Ad_bar;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.Click_ad_listener;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.DataCallback_09;
import com.cmcc.aregister.cs.asntask.MyAsynTaskOther;
import com.cmcc.aregister.cs.cache.AdCache;
import com.cmcc.aregister.cs.cache.CacheManager;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.AdModel;
import com.cmcc.aregister.cs.model.AdbarResultModel;
import com.cmcc.aregister.cs.model.Appointment;
import com.cmcc.aregister.cs.model.ClickAdResultModel;
import com.cmcc.aregister.cs.model.Hospital;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.ui.adapter.ImagePagerAdapter;
import com.cmcc.aregister.ui.view.GestureUtils;
import com.cmcc.aregister.ui.view.GestureUtils.Screen;
import com.cmcc.aregister.ui.view.MultiDirectionSlidingDrawer;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/**
 * 新首页
 * 
 * @author FuLei
 * 
 */
public class NewIndexActivity extends ParentActivity implements OnClickListener
{
    private ViewPager ad_image;// 广告图片
    // private TextView ad_text;// 广告标题
    // private PageControlView page_control;// 广告页数控制
    private LinearLayout btn_more;// 更多
    // private RelativeLayout btn_register;// 预约挂号
    // private RelativeLayout btn_hospital;// 名医名院
    // private RelativeLayout btn_mycenter;// 个人中心
    // private RelativeLayout btn_guide;// 就医导航
    // private RelativeLayout btn_voice;// 语音挂号
    private boolean isFirstCreate = false;
    private String params;
    private List<Appointment> localAppList = new ArrayList<Appointment>();
    private int endTime = 0;
    // private String[] adString;
    private static final String SHAREDPREFERENCES_NAME = "first_pref";

    private DisplayImageOptions options;
    private ImagePagerAdapter mImagePagerAdapter;
    AdbarResultModel mAdbarResultModel;

    MultiDirectionSlidingDrawer mDrawer;
    private GestureDetector gestureDetector;
    private Screen screen;
    private ImageView imgView, dianzanView;
    private TextView countDownView, loginFlagView;
    private RelativeLayout slidingLayout;
    private Rect normal = new Rect();
    private boolean isStart;

    // 首页广告。
    Ad_bar ad_bar = new Ad_bar() {

        @Override
        public void ad_bar_callback(AdbarResultModel model)
        {
            // TODO Auto-generated method stub
            mAdbarResultModel = model;
            if (model.resultCode.equals("0"))
            {
                hasDownBannerAd = true;
                options = new DisplayImageOptions.Builder()
                    .showImageForEmptyUri(R.drawable.ad_default_bg)
                    .cacheOnDisc().imageScaleType(ImageScaleType.EXACT).build();
                mImagePagerAdapter = new ImagePagerAdapter(
                    NewIndexActivity.this, model.ads, options, mDataCallback_09);
                ad_image.setAdapter(mImagePagerAdapter);
                // page_control.count = model.ads.size();
                // page_control.generatePageControl(0);
                ad_image.setOnPageChangeListener(mOnPageChangeListener);
                // ad_text.setText(mAdbarResultModel.ads.get(0).title);
                if (model.ads.size() > 1)
                {
                    bannerStartHandler.postDelayed(bannerStartRun,
                        Integer.parseInt(model.ads.get(0).playtime) * 1000);
                }
            }
            else
            {
                if (model.resultMsg.equals(""))
                {
                    Toast.makeText(NewIndexActivity.this,
                        R.string.network_fail, Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(NewIndexActivity.this, model.resultMsg,
                        Toast.LENGTH_SHORT).show();
                }
            }
        }
    };
    Handler bannerStartHandler = new Handler();
    Runnable bannerStartRun = new Runnable() {

        @Override
        public void run()
        {
            ad_image.setCurrentItem(1);
        }
    };

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (bannerStartHandler != null && bannerStartRun != null)
        {
            bannerStartHandler.removeCallbacks(bannerStartRun);
        }
        entity = null;
    }

    /**
     * 初始化参数
     * 
     * @param parameterMap
     * @return
     */
    private Map<String, String> initArgMap(Map<String, String> parameterMap)
    {
        parameterMap.put("userId", Arguments.UserId_AD);
        parameterMap.put("timestamp", ConfigUtilHelper.getStringNow());
        parameterMap.put("userPwd", ConfigUtilHelper.getAdUserPwd());
        return parameterMap;

    }

    @Override
    protected void onStop()
    {
        ImageLoader.getInstance().stop();
        super.onStop();
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // 初次安装新功能导航
        isFirstCreate = true;
        init(R.layout.new_index);
        gestureDetector = new GestureDetector(this, onGestureListener);
        // 得到屏幕的大小
        screen = GestureUtils.getScreenPix(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        return gestureDetector.onTouchEvent(event);
    };

    GestureDetector.OnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener() {
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY)
        {
            float x = e2.getX() - e1.getX();
            float y = e2.getY() - e1.getY();
            // 限制必须得划过屏幕的1/3才能算划过
            float x_limit = screen.widthPixels / 100;
            float y_limit = screen.heightPixels / 100;
            float x_abs = Math.abs(x);
            float y_abs = Math.abs(y);
            if (x_abs >= y_abs)
            {
                if (x > x_limit || x < -x_limit)
                {
                    if (x > 0)
                    {
                        // right
                        if (mDrawer.isOpened())
                            mDrawer.animateClose();
                    }
                    else if (x <= 0)
                    {
                        // left
                        if (mDrawer.isOpened())
                            mDrawer.animateClose();
                    }
                }
            }
            else
            {
                if (y > y_limit || y < -y_limit)
                {
                    if (y > 0)
                    {
                        countDownView.setVisibility(View.GONE);
                        if (!mDrawer.isOpened())
                            mDrawer.animateOpen();
                    }
                    else if (y <= 0)
                    {
                        if (mDrawer.isOpened())
                            mDrawer.animateClose();
                    }
                }
            }
            return false;
        }

    };

    @Override
    public void onContentChanged()
    {
        mDrawer = (MultiDirectionSlidingDrawer) findViewById(R.id.drawer);
        Intent intent = getIntent();
        isStart = intent.getBooleanExtra("isStart", false);
        if (isStart)
        {
            mDrawer.animateOpen();
        }
        super.onContentChanged();
    }

    @Override
    protected void setupData()
    {
        // adString = getResources().getStringArray(R.array.ad_title);

    }

    // private Drawable loadImageFromNetwork(String urladdr)
    // {
    // // TODO Auto-generated method stub
    // Drawable drawable = null;
    // try
    // {
    // // judge if has picture locate or not according to filename
    // drawable = Drawable.createFromStream(new URL(urladdr).openStream(),
    // "image.jpg");
    // }
    // catch (IOException e)
    // {
    // Log.i("NewIndexActivity", "加载图片时，服务器未找到对应的路径", e);
    // }
    // return drawable;
    // }

    private Timer timer;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);

            // Handler处理消息
            if (msg.what > 0)
            {
                countDownView.setText(msg.what + "");
            }
            else
            {
                timer.cancel();
                countDownView.setVisibility(View.GONE);
                if (mDrawer.isOpened())
                    mDrawer.animateClose();
                autoLogin();
            }
        }
    };

    private void autoLogin()
    {
        if (ConfigUtilHelper.getAutoLogin(this)
            && !ConfigUtilHelper.isLogin(this))
        {
            initLogin();
        }
    }

    @Override
    protected void setupView()
    {
        // 界面控件初始化
        imgView = (ImageView) findViewById(R.id.img_view);
        dianzanView = (ImageView) findViewById(R.id.dianzan);
        countDownView = (TextView) findViewById(R.id.count_down);
        loginFlagView = (TextView) findViewById(R.id.login_flag);
        slidingLayout = (RelativeLayout) findViewById(R.id.start_content_layout);
        // 图片布满整屏
        imgView.setScaleType(ScaleType.FIT_XY);
        ImageCallback callback = new ImageCallback() {
            @Override
            public void imageLoaded(Drawable drawable)
            {
                imgView.setImageDrawable(drawable);
            }
        };
        if (AdCache.imgUrl == "")
        {
            slidingLayout.setVisibility(View.GONE);
        }
        imgView.setImageDrawable(loadDrawable(AdCache.imgUrl, callback));
        if (AdCache.hasUrl.equals("2"))
        {
            dianzanView.setVisibility(View.GONE);
        }
        else
        {
            dianzanView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    // 检查网络链接是否正常，如果没有网络链接，提示链接错误。
                    if (ConfigUtilHelper.checkNetworkState(context) == 0)
                    {
                        Toast.makeText(NewIndexActivity.this,
                            R.string.network_fail, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    dianzan(AdCache.hasUrl, AdCache.scantype, AdCache.areaId,
                        AdCache.adId);
                }
            });
        }

        slidingLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v)
            {
                if (normal.isEmpty())
                {
                    normal.set(slidingLayout.getLeft(), slidingLayout.getTop(),
                        slidingLayout.getRight(), slidingLayout.getBottom());
                }
                // 开启移动动画
                TranslateAnimation ta = new TranslateAnimation(0, 0, -50,
                    normal.top);
                ta.setDuration(1000);
                slidingLayout.startAnimation(ta);
                // 设置回到正常的布局位置
                slidingLayout.layout(normal.left, normal.top, normal.right,
                    normal.bottom);
                normal.setEmpty();
            }
        });
        slidingLayout.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                return gestureDetector.onTouchEvent(event);
            }
        });

        ad_image = (ViewPager) findViewById(R.id.ad_image);
        // ad_text = (TextView) findViewById(R.id.ad_text);
        // page_control = (PageControlView) findViewById(R.id.pageControlView);
        btn_more = (LinearLayout) findViewById(R.id.ly_index_more);
        ImageView btn_hospital = (ImageView) findViewById(R.id.iv_index_menu_hospital);
        ImageView btn_guide = (ImageView) findViewById(R.id.iv_index_menu_guid);
        ImageView btn_mycenter = (ImageView) findViewById(R.id.iv_index_menu_center);
        ImageView btn_register = (ImageView) findViewById(R.id.iv_index_menu_register);
        ImageView btn_voice = (ImageView) findViewById(R.id.iv_index_menu_voice);
        ImageView btn_service = (ImageView) findViewById(R.id.iv_index_menu_service);
        // 设置单击事件监听
        //btn_more.setOnClickListener(this);
        btn_mycenter.setOnClickListener(this);
        btn_hospital.setOnClickListener(this);
        btn_guide.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        btn_voice.setOnClickListener(this);
        btn_service.setOnClickListener(this);
        // 设置长按事件监听
        // btn_more.setOnLongClickListener(onLongClickListener);
        // btn_mycenter.setOnLongClickListener(onLongClickListener);
        // btn_guide.setOnLongClickListener(onLongClickListener);
        // btn_register.setOnLongClickListener(onLongClickListener);
        // btn_hospital.setOnLongClickListener(onLongClickListener);
        // btn_voice.setOnLongClickListener(onLongClickListener);
        ad_image.setCurrentItem(0);

        /** 增加默认广告图片 */
        List<AdModel> defAdModels = new ArrayList<AdModel>();
        defAdModels.add(new AdModel());
        options = new DisplayImageOptions.Builder()
            .showImageForEmptyUri(R.drawable.ad_default_bg).cacheOnDisc()
            .imageScaleType(ImageScaleType.EXACT).build();
        mImagePagerAdapter = new ImagePagerAdapter(this, defAdModels, options,
            mDataCallback_09);
        ad_image.setAdapter(mImagePagerAdapter);

    }

    public Drawable loadDrawable(final String imgUrl,
        final ImageCallback callback)
    {

        if (AdCache.imageCache.containsKey(imgUrl))
        {
            SoftReference<Drawable> sf = AdCache.imageCache.get(imgUrl);

            if (sf.get() != null)
            {
                return sf.get();
            }
        }

        final Handler handler = new Handler() {

            public void handleMessage(Message msg)
            {
                callback.imageLoaded((Drawable) msg.obj);
            }
        };

        new Thread() {

            public void run()
            {
                Drawable drawable = loadImageFromNetwork(imgUrl);
                if (drawable != null)
                {

                    AdCache.imageCache.put(imgUrl, new SoftReference<Drawable>(
                        drawable));
                    Message msg = handler.obtainMessage(0, drawable);
                    handler.sendMessage(msg);
                }
            }

        }.start();
        return null;
    }

    public interface ImageCallback
    {

        public void imageLoaded(Drawable drawable);

    }

    private void initLogin()
    {
        Intent intent = new Intent(this, UserLoginActivity.class);
        intent.putExtra(Arguments.AUTO_LOGIN, true);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int i,
            long l)
        {
            gotoHospitalDetail(i);
        }
    };

    /**
     * 进入医院详情
     * 
     * @param type
     * @param area_type
     * @param uuid
     * @param positon
     */
    private void gotoHospitalDetail(int i)
    {
        Hospital hospital = MyApplication.getInstance().adHospitals.get(i);
        Map<String, Object> httpMap = new HashMap<String, Object>();
        PotoalParcelable potoal = new PotoalParcelable(httpMap);
        Intent intent = null;
        intent = new Intent(NewIndexActivity.this, HospitalDetailActivity.class);
        httpMap.put(Arguments.ACTIVITY_JUMP_HOSPITAL, hospital);
        httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE, hospital.area_type);
        httpMap.put(Arguments.ACTIVITY_JUMP_POSITION, i);
        intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void startAnimal(View view)
    {
        View newView = view;
        Animation animation = AnimationUtils.loadAnimation(this,
            R.anim.my_scale_action);
        newView.startAnimation(animation);
    }

    // OnLongClickListener onLongClickListener = new OnLongClickListener() {
    //
    // @Override
    // public boolean onLongClick(View v)
    // {
    // int id = v.getId();
    // Intent intent = null;
    // int menu_id = 0;
    // switch (id)
    // {
    // case R.id.ry_index_menu_register:
    // intent = new Intent(NewIndexActivity.this, MainActivity.class);
    // menu_id = 0;
    // break;
    // case R.id.ry_index_menu_hospital:
    // intent = new Intent(NewIndexActivity.this, MainActivity.class);
    // menu_id = 1;
    // break;
    // case R.id.ry_index_menu_myservice:
    // intent = new Intent(NewIndexActivity.this, MainActivity.class);
    // menu_id = 2;
    // break;
    // case R.id.ry_index_menu_guid:
    // intent = new Intent(NewIndexActivity.this, MainActivity.class);
    // menu_id = 3;
    // break;
    // case R.id.ly_index_more:
    // intent = new Intent(NewIndexActivity.this, MainActivity.class);
    // menu_id = 4;
    // break;
    // case R.id.ly_index_voice:
    // intent = new Intent(NewIndexActivity.this, MainActivity.class);
    // menu_id = 5;
    // break;
    // }
    // intent.putExtra(Arguments.INTENT_TO_MAIN_ID, menu_id);
    // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // if (id != R.id.ly_index_more && id != R.id.ly_index_voice)
    // {
    // startAnimal(v);
    // begin(intent);
    // }
    // else
    // {
    // startActivity(intent);
    // }
    // return false;
    // }
    // };

    /**
     * 睡眠2秒后进入主页
     */
    private void begin(final Intent intent)
    {
        AsyncTask<String, Integer, String> task = new AsyncTask<String, Integer, String>() {
            protected String doInBackground(String... params)
            {
                try
                {
                    Thread.sleep(300);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                return null;
            }

            protected void onPostExecute(String result)
            {
                startActivity(intent);
            }
        };
        task.execute("");
    }

    boolean hasDownBannerAd = false;

    @Override
    protected void onResume()
    {
        super.onResume();
        if (!ConfigUtilHelper.isLogin(app))
        {
            loginFlagView.setText(R.string.unlogin);
        }
        else
        {
            loginFlagView.setText(R.string.islogin);
        }
        SharedPreferences preferences = getSharedPreferences(
            SHAREDPREFERENCES_NAME, MODE_PRIVATE);
        Editor editor = preferences.edit();
        int count = preferences.getInt("count", 0);
        editor.putInt("count", ++count);
        editor.commit();
        if (count == 1)
        {
            Intent intent = new Intent(NewIndexActivity.this,
                UserGuideActivity.class);
            startActivity(intent);
            return;
        }
        if (isStart)
        {
            timer = new Timer();
            if (!"".equals(AdCache.playtime))
            {
                endTime = Integer.parseInt(AdCache.playtime);
                TimerTask timerTask = new TimerTask() {
                    // 倒数10秒
                    @Override
                    public void run()
                    {
                        // 定义一个消息传过去
                        Message msg = new Message();
                        msg.what = endTime--;
                        handler.sendMessage(msg);
                    }
                };
                timer.schedule(timerTask, 0, 1000);// 3秒后开始倒计时，倒计时间隔为1秒
            }
        }
        isStart = false;
        /*
         * if (ConfigUtilHelper.isLogin(app)) {
         * login_btn.setVisibility(View.GONE); } else {
         * login_btn.setVisibility(View.VISIBLE); }
         */
        if (!hasDownBannerAd)
        {// 如果没有加载广告条
            Map<String, String> parameterMap = new HashMap<String, String>();
            parameterMap = initArgMap(parameterMap);
            parameterMap.put("methodVit", Arguments.GetAdBar);
            parameterMap.put("areaId", Arguments.AreaId);
            new MyAsynTaskOther(ad_bar, GlobalSetting.AD_BAR, parameterMap)
                .execute();
        }
        if (ConfigUtilHelper.isConnectingToInternet(this))
        {
            // 检测版本更新
            new GetDataTask().execute();
        }
        sendGetOrderInfoTask();
    }

    private HttpAsyncTask sendGetOrderInfoTask;

    private void sendGetOrderInfoTask()
    {
        logger.d("----------sendGetOrderInfoTask----------");
        JSONObject obj = new JSONObject();
        try
        {
            obj.put("request_type", Arguments.QueryAppointTaskRemoting);
            obj.put("user_mobile", ConfigUtilHelper.getMobile(app));
            obj.put("channel", "medical_client_android");
            obj.put("version",
                ConfigUtilHelper.getVersionName(getApplication()));
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        params = obj.toString();
        String url = Arguments.GET_AUTO_APPOINT_SERVICE_URL;
        sendGetOrderInfoTask = new HttpAsyncTask(
            GlobalSetting.XML_AUTO_APPOINT_LIST, url, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true, true);
        // showProgressDialogNew(R.string.dialog_loading_auto_appoints);
        sendGetOrderInfoTask.setUIHandler(sendGetOrderInfoTaskHandler);
        mHttpManager.execute(sendGetOrderInfoTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetOrderInfoTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendGetOrderInfoTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                // dismissProgressDialog();
                if (msg.obj != null)
                {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    localAppList = (List<Appointment>) httpMap
                        .get(Arguments.JSON_AUTO_APPOINT_LIST);
                    int i = 0;
                    for (Appointment app : localAppList)
                    {
                        if (app.yuyue_state.equals("2")
                            || app.yuyue_state.equals("3")
                            || app.yuyue_state.equals("5"))
                        {
                            Object obj = CacheManager.getInstance()
                                .queryAutoCache(app.yuyue_id);
                            if (obj == null)
                            {
                                CacheManager.getInstance().saveAutoCache(
                                    app.yuyue_id, app.phone, app.begin_time);
                                i++;
                            }
                        }
                    }
                    if (i > 1)
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.auto_tip),
                            getString(R.string.close));
                    }
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    private class GetDataTask extends AsyncTask<Void, Void, String[]>
    {

        // 任务在后台执行
        @Override
        protected String[] doInBackground(Void... params)
        {
            String appversion = ConfigUtilHelper.getVersionName(app);
            String url = Arguments.CHECK_UPDATE_URL;
            entity = ConfigUtilHelper.getUpdateMsg(url, "8",
                "wxcityMobileClient", "2", appversion);
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values)
        {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);

        }

        // 任务执行的结果
        @Override
        protected void onPostExecute(String[] result)
        {
            if (entity.Status != null && entity.Status.equals("1"))
            {
                if (entity.State.equals("0"))
                {
                    showAlertDlg_update(
                        getString(R.string.dialog_update_title),
                        entity.Content,
                        getString(R.string.dialog_update_later),
                        getString(R.string.dialog_update_now), entity.DownLink);
                }
                else if (entity.State.equals("1"))
                {
                    showAlert_update(getString(R.string.dialog_update_title),
                        entity.Content, getString(R.string.dialog_update_now),
                        entity.DownLink);
                }
            }
        }
    }

    @Override
    public void onClick(View v)
    {
        int id = v.getId();
        Intent intent = null;
        int menu_id = 0;
        switch (id)
        {
        case R.id.iv_index_menu_register:
            if (!ConfigUtilHelper.isLogin(NewIndexActivity.this))
            {
                gotoLogin();
                return;
            }
            intent = new Intent(NewIndexActivity.this, MainActivity.class);
            menu_id = 0;
            break;
        case R.id.iv_index_menu_hospital:
            intent = new Intent(NewIndexActivity.this, MainActivity.class);
            menu_id = 1;
            break;
        case R.id.iv_index_menu_center:
            if (!ConfigUtilHelper.isLogin(NewIndexActivity.this))
            {
                gotoLogin();
                return;
            }
            intent = new Intent(NewIndexActivity.this, MainActivity.class);
            menu_id = 2;
            break;
        case R.id.iv_index_menu_guid:
            intent = new Intent(NewIndexActivity.this, MainActivity.class);
            menu_id = 3;
            break;
        case R.id.ly_index_more:
        case R.id.iv_index_menu_service:
            intent = new Intent(NewIndexActivity.this, MainActivity.class);
            menu_id = 4;
            break;
        case R.id.iv_index_menu_voice:
            if (!ConfigUtilHelper.isLogin(NewIndexActivity.this))
            {
                gotoLogin();
                return;
            }
            intent = new Intent(NewIndexActivity.this, MainActivity.class);
            menu_id = 5;
            break;
        }
        intent.putExtra(Arguments.INTENT_TO_MAIN_ID, menu_id);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (id != R.id.ly_index_more && id != R.id.ly_index_voice)
        {
            startAnimal(v);
            begin(intent);
        }
        else
        {
            startActivity(intent);
        }
    }

    /**
     * 刷新广告图片
     */
    Handler galleryHandler = new Handler() {
        @Override
        public void handleMessage(Message msg)
        {
            int position = (Integer) msg.obj + 1;
            /*
             * if (position < 4) { ad_image.setSelection(position); } else {
             * ad_image.setSelection(0); }
             */
            ad_image.setCurrentItem(position);
        }
    };

    OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
            int position, long arg3)
        {
            // page_control.generatePageControl(position);
            // ad_text.setText(adString[position]);
            galleryHandler.removeMessages(0);
            galleryHandler.sendMessageDelayed(
                galleryHandler.obtainMessage(0, position), 2000);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0)
        {

        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
        case KeyEvent.KEYCODE_BACK:
            showConfirmDialog(R.string.logout_info);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 跳转到登陆界面
    private void gotoLogin()
    {
        Intent intent = new Intent(NewIndexActivity.this,
            UserLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    /**
     * 首页下拉广告点赞
     * @param hasUrl
     * @param areaId
     * @param adId
     */
    private void dianzan(String hasUrl, String scantype, String areaId,
        String adId)
    {
        if (hasUrl.equals("1") && scantype.equals("1"))
        {
            showProgressDialog();
            Map<String, String> parameterMap = new HashMap<String, String>();
            parameterMap = initArgMap(parameterMap);
            parameterMap.put("methodVit", Arguments.GetClickAdBar);
            parameterMap.put("areaId", areaId);
            parameterMap.put("adId", adId);
            new MyAsynTaskOther(dianzanAd_listener, GlobalSetting.CLICK_AD_BAR,
                parameterMap).execute();
        }
    }

    /**
     * 点赞回调
     */
    Click_ad_listener dianzanAd_listener = new Click_ad_listener() {

        @Override
        public void click_ad_callback(ClickAdResultModel mClickAdResultModel)
        {
            dismissProgressDialog();
            if (mClickAdResultModel.resultCode.equals("0"))
            {
                Intent intent = new Intent(NewIndexActivity.this,
                    MyWebView.class);
                intent.putExtra("url", mClickAdResultModel.url);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        }
    };

    int bannerCurrentPosition;
    /**
     * banner点击事件回调
     */
    DataCallback_09 mDataCallback_09 = new DataCallback_09() {

        @Override
        public void callback(int p)
        {
            // TODO Auto-generated method stub
            if (hasDownBannerAd
                && mAdbarResultModel.ads.get(p).hasAdUrl.equals("1"))
            {
                bannerCurrentPosition = p;
                showProgressDialog();
                Map<String, String> parameterMap = new HashMap<String, String>();
                parameterMap = initArgMap(parameterMap);
                parameterMap.put("methodVit", Arguments.GetClickAdBar);
                parameterMap.put("areaId", Arguments.AreaId);
                parameterMap.put("adId", mAdbarResultModel.ads.get(p).id);
                new MyAsynTaskOther(mClick_ad_listener,
                    GlobalSetting.CLICK_AD_BAR, parameterMap).execute();
            }

        }
    };

    Click_ad_listener mClick_ad_listener = new Click_ad_listener() {

        @Override
        public void click_ad_callback(ClickAdResultModel mClickAdResultModel)
        {
            dismissProgressDialog();
            // TODO Auto-generated method stub
            if (mClickAdResultModel.resultCode.equals("0"))
            {
                if (mAdbarResultModel.ads.get(bannerCurrentPosition).scantype
                    .equals("1")
                    && mAdbarResultModel.ads.get(bannerCurrentPosition).hasAdUrl
                        .equals("1"))
                {
                    String url = mClickAdResultModel.url;
                    if (url
                        .contains("http://wap.szicity.com/cm/yezhi/index.aspx"))
                    {
                        Intent intent = new Intent(NewIndexActivity.this,
                            YdzqWebsiteLoading.class);
                        intent.putExtra("fromAdPage", true);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                    else
                    {
                        Intent intent = new Intent(NewIndexActivity.this,
                            MyWebView.class);
                        intent.putExtra("url", url);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                }
            }
        }
    };

    /**
     * viewPage切换
     */
    OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position)
        {
            // TODO Auto-generated method stub

            if (mAdbarResultModel.ads.size() > 0)
            {
                int p = position % mAdbarResultModel.ads.size();
                // page_control.generatePageControl(p);
                // ad_text.setText(mAdbarResultModel.ads.get(p).title);
                galleryHandler.removeMessages(0);
                int playTime = 2 * 1000;
                if (!mAdbarResultModel.ads.get(p).playtime.equals(""))
                {
                    playTime = Integer
                        .parseInt(mAdbarResultModel.ads.get(p).playtime) * 1000;
                }
                galleryHandler.sendMessageDelayed(
                    galleryHandler.obtainMessage(0, position), playTime);
            }

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0)
        {
            // TODO Auto-generated method stub

        }
    };
}